<template>
  <div class="region-selector">
    <div class="header">
      <i class="el-icon-back" @click="goBack"></i>
      <span>选择地区</span>
    </div>
    <div class="current-location">
      <span>当前定位城市</span>
      <i class="el-icon-location-pin"></i>
      <span class="cheng">{{ currentCity }}</span>
    </div>
    <div class="hot-regions">
      <span>热门地区</span>
      <div class="region-buttons">
        <button v-for="(region, index) in hotRegions" :key="index" @click="selectRegion(region)">
          {{ region.name }}
        </button>
      </div>
    </div>
    <div class="all-regions">
      <span>所有地区</span>
      <van-index-bar>
        <!-- 使用 v-for 动态渲染 van-index-anchor 和 van-cell -->
        <template v-for="(group, index) in groupedData">
          <van-index-anchor :index="group.index" :key="`anchor-${index}`" />
          <van-cell
              v-for="(item, itemIndex) in group.items"
              :title="item.title"
              :key="`cell-${index}-${itemIndex}`"
              @click="selectRegion1(item)"
          />
        </template>
      </van-index-bar>
      <!--      <div class="region-list-container">-->
      <!--        <ul class="region-list-content" ref="regionListContent">-->
      <!--          <li v-for="(group, groupIndex) in allRegions" :key="groupIndex" :id="`region - group - ${group.letter}`">-->
      <!--            <div class="region-group-header">-->
      <!--              {{ group.letter }}-->
      <!--            </div>-->
      <!--            <ul>-->
      <!--              <li v-for="(region, regionIndex) in group.regions" :key="regionIndex" @click="selectRegion(region)">-->
      <!--                {{ region.name }}-->
      <!--              </li>-->
      <!--            </ul>-->
      <!--          </li>-->
      <!--        </ul>-->
      <!--        <ul class="region-list-alphabet">-->
      <!--          <li v-for="letter in alphabetList" :key="letter" @click="scrollToRegion(letter)" :class="{ 'selected-letter': currentSelectedLetter === letter }">-->
      <!--            {{ letter }}-->
      <!--          </li>-->
      <!--        </ul>-->
      <!--      </div>-->
    </div>
  </div>
</template>

<script>
// region - selector.vue
import axios from 'axios';

export default {
  data() {
    return {
      currentCity: '未知',
      hotRegions: '',
      allRegions: [],
      alphabetList: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
      currentSelectedLetter: null,
      amapKey: 'cdf6b6e03227b2266836d42a37873972',
      groupedData: [] // 存储处理后的数据
    };
  },
  mounted() {
    // this.getLocation();
    this.fetchAllRegions();
    this.fetchHotRegions();
    this.fetchData();
    this.currentCity = localStorage.getItem('currentCity');
  },

  created(){
    const token = JSON.parse(localStorage.getItem("token"));
    if (!token) {
      this.$message.error('请先登录');
      setTimeout(() => {
        this.$router.push({name: 'login'});
      }, 666);
    }
    // 设置全局默认请求头
    this.axios.defaults.headers.common['token'] = token;
    this.findAddress();
    console.log("1"+this.currentCity)
    this.getCoordsByRegionName(this.currentCity);
  },


  methods: {
    findAddress(){
      this.axios.get('http://localhost:10086/api/user/user/getUserLocation').then((response) => {
        if (response.data.code === 200) {
          this.currentCity = response.data.data;
        }
      });
    },
    updateAddress(address){
      this.axios.put('http://localhost:10086/api/user/user/updateUserAddress?address='+address).then((response) => {

      });
    },
    fetchHotRegions() {
      axios.get('http://localhost:10086/api/user/region/getHotRegions').then((response) => {
        this.hotRegions = response.data;
      }).catch((error) => {
        console.error('获取热门地区失败:', error);
      });
    },
    async fetchData() {
      try {
        // 发送异步请求获取后端数据
        const response = await axios.get(`http://localhost:10086/api/user/region/findAll`);
        const data = response.data;

        // 假设后端返回的数据格式为数组，每个元素包含 index 和 items 字段
        this.groupedData = data;

      } catch (error) {
        console.error('获取数据失败:', error);
      }
    },
    fetchAllRegions() {
      axios.get('http://localhost:10086/api/user/region/getAllRegions').then((response) => {
        const regions = response.data;
        const groupedRegions = {};
        regions.forEach((region) => {
          const firstChar = region.name.charAt(0).toUpperCase();
          if (!groupedRegions[firstChar]) {
            groupedRegions[firstChar] = { letter: firstChar, regions: [] };
          }
          groupedRegions[firstChar].regions.push(region);
        });
        this.allRegions = Object.values(groupedRegions);
        // 数据处理：将地区名称首字替换为字母
        this.allRegions.forEach(group => {
          group.regions.forEach(region => {
            const firstChar = region.name.charAt(0).toUpperCase();
            region.formattedName = firstChar + region.name.slice(1);
          });
        });
      }).catch((error) => {
        console.error('获取地区数据失败:', error);
      });
    },

    async getCoordsByRegionName(regionName) {
      // const url = `https://restapi.amap.com/v3/geocode/geo?address=${regionName}&key=${this.amapKey}`;
      // axios.get(url,)

      axios.get('https://restapi.amap.com/v3/geocode/geo', {
        params: {
          address: regionName,
          key: this.amapKey
        },headers: {
          // 移除 token 请求头，这里将 token 字段设为 undefined 即可
          token: undefined
        }
      }).then((response) => {
        if (response.data.status === '1' && response.data.geocodes.length > 0) {
          const location = response.data.geocodes[0].location;
          const [longitude, latitude] = location.split(',');
          console.log('选中地区经纬度:', latitude, longitude);
        } else {
          console.error('获取经纬度失败:', response.data);
        }
      }).catch((error) => {
        console.error('获取经纬度出错:', error);
      });
    },
    selectRegion(region) {
      this.currentCity = region.name;
      console.log('选中地区:', region.name)
      localStorage.setItem('currentCity', region.name);
      this.getCoordsByRegionName(region.name);

      console.log('选中地区:', region.name);
      this.updateAddress(region.name)
      // 跳转到 nearby - institutions 页面并传递地区名称
      this.$router.push({
        name: 'index',
        //传入名称
        query: { regionName: region.name }
      }).then(() => {
        window.location.reload();
      });
    },
    selectRegion1(region) {
      if (!region || !region.title) {
        console.error('无效的地区信息');
        return;
      }
      this.currentCity = region.title;
      localStorage.setItem('currentCity', region.title);
      this.getCoordsByRegionName(region.title);
      console.log('选中地区:', region.title);
      // 跳转到 nearby - institutions 页面并传递地区名称
      this.$router.push({
        name: 'index',
        //传入名称
        query: { regionName: region.title }
      });
    },
    goBack() {
      this.$router.back();
    },
    scrollToRegion(letter) {
      this.currentSelectedLetter = letter;
      this.$nextTick(() => {
        const target = document.getElementById(`region - group - ${letter}`);
        const regionListContent = this.$refs.regionListContent;
        if (target && regionListContent) {
          const targetTop = target.offsetTop;
          regionListContent.scrollTop = targetTop;
        }
      });
    }
  }
};
</script>

<style scoped>
.cheng{
  font-size: 18px;
  color: #2984F8;
  font-weight: bold;
}
.region-selector {
  background-color: #fff;
  height: 100vh;
}

.header {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 15px;
  border-bottom: 1px solid #e4e7ed;
}

.header i {
  font-size: 20px;
  margin-right: 10px;
}

.current-location {
  display: flex;
  align-items: center;
  height: 40px;
  padding: 0 15px;
  border-bottom: 1px solid #e4e7ed;
}

.current-location i {
  font-size: 18px;
  margin: 0 10px;
}

.hot-regions {
  padding: 15px;
}

.hot-regions span {
  display: block;
  font-size: 18px;
  margin-bottom: 10px;
}

.region-buttons button {
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 8px 16px;
  border: 1px solid #ccc;
  border-radius: 50px;
  background-color: #f9f9f9;
  font-size: 14px;
}

.all-regions {
  padding: 0 15px;
}

.all-regions span {
  display: block;
  font-size: 18px;
  margin-bottom: 10px;
  margin-top: 15px;
}

.region-list-container {
  display: flex;
  justify-content: space-between;
}

.region-list-alphabet {
  list-style: none;
  width: 20px;
}

.region-list-alphabet li {
  line-height: 20px;
}

.region-list-content {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 340px;
  text-align: left;
  overflow-y: auto;
  max-height: calc(100vh - 134px);
}

.region-group-header {
  font-size: 16px;
  margin-bottom: 5px;
}

.region-list-content ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.region-list-content li {
  margin-bottom: 5px;
}

.selected-letter {
  background-color: #2984F8;
  color: white;
  border-radius: 50%;
  text-align: center;
}
</style>